package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

type Result2 struct {
	Abstract    string          `json:"abstract"`
	AuthorIntro string          `json:"author_intro"`
	BookIntro   string          `json:"book_intro"`
	Catalog     json.RawMessage `json:"catalog"`
	Comments    []struct {
		Content  string `json:"content"`
		Rate     string `json:"rate"`
		Time     string `json:"time"`
		UserName string `json:"user_name"`
		UserPage string `json:"user_page"`
		UserPic  string `json:"user_pic"`
		Vote     string `json:"vote"`
	} `json:"comments"`
	CoverURL      string   `json:"cover_url"`
	CreateTime    string   `json:"create_time"`
	Isbn          string   `json:"isbn"`
	Labels        []string `json:"labels"`
	OriginalTexts []string `json:"original_texts"`
	Rating        struct {
		Count      float64 `json:"count"`
		RatingInfo string  `json:"rating_info"`
		StarCount  float64 `json:"star_count"`
		Value      float64 `json:"value"`
	} `json:"rating"`
	Source string `json:"source"`
	Title  string `json:"title"`
	URL    string `json:"url"`
}

func QueryIsbn2(isbn string) ([]*BookItem, error) {
	if len(isbn) == 0 {
		return nil, errors.New("isbn 为空")
	}
	var isbnUrl = "http://book.feelyou.top/isbn/"
	req, err := http.NewRequest("GET", isbnUrl+isbn, nil)
	if err != nil {
		return nil, err
	}
	q := req.URL.Query()
	q.Add("isbn", isbn)
	req.URL.RawQuery = q.Encode()
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	resJsonStr, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	var resObj Result2
	err = json.Unmarshal(resJsonStr, &resObj)
	if err != nil {
		fmt.Println(string(resJsonStr))
		return nil, err
	}
	if resObj.Title == "" {
		fmt.Println(string(resJsonStr))
		return nil, errors.New("调用接口失败")
	}
	var bookItem BookItem
	bookItem.Isbn = isbn
	bookItem.Count = 2
	bookItem.Title = resObj.Title
	// 解析信息 "abstract": "太宰治 / 杨伟 / 作家出版社 / 2015-8 / 25.00元",
	filed := strings.Fields(resObj.Abstract)
	if len(filed) >= 7 {
		bookItem.AuthorName = filed[len(filed)-7]
		bookItem.Publisher = filed[len(filed)-5]
		bookItem.Published = filed[len(filed)-3]
		bookItem.Price = filed[len(filed)-1]
	}
	// 没有的信息
	bookItem.Logo = "resObj.Logo"
	bookItem.Page = "resObj.Page"
	bookItem.Designed = "resObj.Designed"
	bookItem.Description = resObj.BookIntro
	return []*BookItem{&bookItem}, nil
}
